<?php
namespace app\admin\controller\csmding;

use addons\csmding\library\CsmContants;
use app\common\controller\Backend;
use fast\Random;
use think\Session;
use addons\csmding\library\dingtalk\DingTalkClient;
use addons\csmding\library\dingtalk\DingTalkConstant;
use addons\csmding\library\dingtalk\OapiSnsGetuserinfoBycodeRequest;
use addons\csmding\library\dingtalk\OapiUserGetuserinfoRequest;
use addons\csmding\library\Csmding;
use think\Request;
use think\Hook;
use think\Db;

use app\common\library\Auth as Apiauth;

class Ddlogin extends Backend
{
    protected $noNeedLogin = [
        '*'
    ];
    public function _initialize()
    {
        parent::_initialize();
    }
    public function active()
    {}
    /**
     * https://csmding.163fan.com/adtoAEYyUj.php/csmding/ddlogin/mobilelogin
     * http://133.fa.net/CouGcOjdYV.php/csmding/ddlogin/mobilelogin
     * 钉钉容器内登录，包括PC登录和手机钉钉容器
     * @return void
     */
    public function mobilelogin()
    {
        $url = $this->request->request("url");
        if(!$url){
            $url = '/root.php';
        }
      
        if ($this->request->isPost()) {
            $code = $this->request->request("code");
            trace("=loginTmpCode1>{$code}");
            $respdduser = $this->getUserInfoByCode($code);
            trace("=loginTmpCode2>{$respdduser->errcode}");
            if ($respdduser != null && $respdduser->errcode == 0) {
                $dao = new \app\admin\model\csmding\Dduser();
                $row = $dao->where('userid', '=', $respdduser->userid)->find();
                Db::name('aa')->insert(['query'=>json_encode($respdduser)]);
                if ($row != null) {
                    // if($row->fauser_id){
                    //     $dao2 = new \app\admin\model\User();
                    //     (new Apiauth())->direct($row->fauser_id);
                    //     $data = ['userinfo' => (new Apiauth())->getUserinfo()];
                    //     return json_encode(['code'=>1,$data]);
                    // }else{
                        $dao2 = new \app\admin\model\Admin();
                        $row2 = $dao2->where('id', '=', $row->faadmin_id)->find();
                        if ($row2 != null) {
                            $this->directLogin($row2);
                            return $this->success('','',['result_code'=>'loginsuccess']);

                            // return $this->success('aa','/dashboard',['result_code'=>'loginsuccess']);
                        }else{
                            //钉钉容器内登录没有绑定账号时，用于在adminLoginAfter登录后绑定的用户key
                            //JS跳转到登录页面
                            trace("set csmding_login_dduserid=".$respdduser->userid);
                            Session::set(CsmContants::$adminLoginAfterdduserkey,$respdduser->userid);//"manager2637"
                             Db::name('aa')->insert(['query'=>22]);
                            return $this->success('bb','/dashboard',['result_code'=>'needlogin']);
                        }
                    // }
                }
            }
            return $this->error('当前账号不可登录后台，请联系管理员同步通讯录！'); 
        }
        $config = get_addon_config("csmding");
        $ddcorpId = $config["ddcorpId"];
        $this->assignconfig('ddcorpId', $ddcorpId);
        $this->assignconfig("url", $url);
        $this->assign("helpimg", "/assets/addons/csmding/img/ding.png");
        $this->assign('title', '钉钉扫码登录');
        return $this->view->fetch();
    }

    public function waplogin()
    {
          $code = $this->request->request("code");
          
          trace("=loginTmpCode1>{$code}");
            $respdduser = $this->getUserInfoByCode($code);
            trace("=loginTmpCode2>{$respdduser->errcode}");
            if ($respdduser != null && $respdduser->errcode == 0) {
                $dao = new \app\admin\model\csmding\Dduser();
                $row = $dao->where('userid', '=', $respdduser->userid)->find();
                Db::name('aa')->insert(['query'=>json_encode($respdduser)]);
                if ($row != null) {
                    if($row->fauser_id){
                        $dao2 = new \app\admin\model\User();
                        (new Apiauth())->direct($row->fauser_id);
                        $data = ['userinfo' => (new Apiauth())->getUserinfo()];
                        return json_encode(['code'=>1,$data]);
                }
            }
            return json_encode(['code'=>0,'msg'=>'当前账号不可登录手机端,请联系管理员同步通讯录！']);
    }
}
    // /**
    //  * 容器内钉钉登录无账号，跳转此处做Admin的账号绑定
    //  * （代码基本参照admin的login）
    //  * @return void
    //  */
    // public function mobileloginbindaccount(){
    //     $url = $this->request->get('url', 'index/index');
    //     if ($this->auth->isLogin()) {
    //         $this->success(__("You've logged in, do not login again"), $url);
    //     }
    //     if ($this->request->isPost()) {
    //         $username = $this->request->post('username');
    //         $password = $this->request->post('password');
    //     }
    // }

    /**
     * http://127.0.0.1/fastadmin_plugin_csmmeet/public/q3HJDu2RgE.php/csmding/ddlogin/dobydd
     * http://fatest.163fan.com/iyjHrvTU3q.php/csmding/ddlogin/dobydd
     */
    public function dobydd()
    {
        $url = $this->request->get('url');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }

        // 安装了csmadmin后,钉钉登录需要显示csmadmin的登录tab
        $urlmenu = $this->request->request('urlmenu');
        $urlmenuarr = [];
        if ($urlmenu != null && $urlmenu != '') {
            $urlmenuarr = json_decode($urlmenu, true);
        }
        $this->assign('ulmenu', $urlmenuarr);
        // 显示钉钉登录画面
        $getparam = ($url == null || $url == '') ? '?1=1' : '?url=' . urlencode($url);
        $ulmenu2 = [
            [
                'name' => '钉钉登录',
                'code' => 'dobydd',
                'url' => 'dobydd' . $getparam
            ]
        ];
        $this->assign('ulmenu2', $ulmenu2);

        $this->assign('title', "用户登录");
        // $this->view->engine->layout('csmadmin/layout/default');
        // copy from Csmadminapp#modifydddialog
        $config = get_addon_config('Csmding');
        $ddappid = $config['ddappid'];
        $this->assign("ddappid", $ddappid);
        //$this->assign("hosturl", $_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"] . ( ($_SERVER["SERVER_PORT"]=='80'||$_SERVER["SERVER_PORT"]=='443')?'':':'.$_SERVER["SERVER_PORT"]));
		//v1.0.7 修复了在服务器设置问题造成无法获取到当前域名的问题
		$this->assign("hosturl", $_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["HTTP_HOST"]);
        return $this->view->fetch();
    }

    /**
     * 用户扫码后,钉钉重定向进入完成登录
     * http://127.0.0.1/fastadmin_plugin_csmmeet/public/q3HJDu2RgE.php/csmding/ddlogin/dobyddtologin
     */
    public function dobyddtologin()
    {
        $url = $this->request->request('url');
        $url = ($url == null || $url == '') ? url('index/index') : $url;

        if ($this->request->isAjax()) {
            $username = strtolower($this->request->request('username'));
            $password = $this->request->request('password');
            $captcha = $this->request->request("captcha", true);
            $captchaResult = \think\Validate::is($captcha, 'captcha');
            if (! $captchaResult) {
                $this->error('验证码不正确');
            }
            // 更新帐号username和password
            $dao = new \app\admin\model\Admin();
            $rowtmp = $dao->where('username', '=', $username)->find();
            if ($rowtmp) {
                $this->error('账号名存在');
            }
            $salt = Random::alnum();
            $dao->where('id', '=', $this->auth->id)->update([
                'username' => $username,
                'salt' => $salt,
                'password' => md5(md5($password) . $salt)
            ]);

            // 设置faisfilladmin状态：已经写入username
            $dao = new \app\admin\model\csmding\Dduser();
            $dao->where('faadmin_id', '=', $this->auth->id)->update([
                'faisfilladmin' => 'true'
            ]);

            $this->success();
            return;
        }

        // 用户扫码后,钉钉重定向进入
        $loginTmpCode = $this->request->request("code");
        $respdduser = $this->getUserInfoByLoginTmpCode($loginTmpCode);
        if ($respdduser != null) {
            $param = [
                'unionid' => $respdduser->unionid
            ];

            if ($param != null) {
                $dao = new \app\admin\model\csmding\Dduser();
                $row = $dao->alias('t')
                    ->join('admin a', "t.faadmin_id=a.id and a.status='normal'")
                    ->field('t.id,a.username,t.faisactivie,t.faadmin_id,t.faisfilladmin')
                    ->where('unionid', '=', $param['unionid'])
                    ->find();
                if ($row) {
                    $dao->where('id', '=', $row->id)->update([
                        'faisactivie' => 'true'
                    ]);
                    $daoadmin = new \app\admin\model\Admin();
                    $row2 = $daoadmin->where('id', '=', $row->faadmin_id)->find();
                    $this->directLogin($row2);
                    if ($row->faisfilladmin == 'false') {
                        // 跳转到激活页面

                        $this->assign('$row', $row);
                        $this->assign('row2', $row2);
                        return $this->view->fetch();
                    } else {
                        $this->redirect($url);
                    }
                }
            }
            $this->error('帐号不存在,请重新登录!');
        }
    }

    public function sendddlogintmpcode()
    {
        $loginTmpCode = $this->csmreq("code", true);
        $row = $this->getUserInfoByLoginTmpCode($loginTmpCode);
        $this->assign("row", $row);
        return $this->view->fetch();
    }

    private static function getUserInfoByCode($code)
    {
        $access_token = Csmding::getAccessToken();

        $c = new DingTalkClient(DingTalkConstant::$CALL_TYPE_OAPI, DingTalkConstant::$METHOD_GET, DingTalkConstant::$FORMAT_JSON);
        $req = new OapiUserGetuserinfoRequest();
        $req->setCode($code);
        $resp = $c->execute($req, $access_token, "https://oapi.dingtalk.com/user/getuserinfo");

        if ($resp != null && $resp->errcode == 0) {
            return $resp;
        } else {
            return null;
        }
    }

    private static function getUserInfoByLoginTmpCode($loginTmpCode)
    {
        $config = get_addon_config("csmding");
        $ddappid = $config["ddappid"];
        $ddappsecret = $config["ddappsecret"];

        $c = new DingTalkClient(DingTalkConstant::$CALL_TYPE_OAPI, DingTalkConstant::$METHOD_POST, DingTalkConstant::$FORMAT_JSON);
        $req = new OapiSnsGetuserinfoBycodeRequest();
        $req->setTmpAuthCode($loginTmpCode);
        $resp = $c->executeWithAccessKey($req, "https://oapi.dingtalk.com/sns/getuserinfo_bycode", $ddappid, $ddappsecret);
        if ($resp != null && $resp->errcode == 0) {
            return $resp->user_info;
        } else {
            return null;
        }
    }

    private function directLogin($admin, $keeptime = 86400)
    {
        // Copy from app\admin\library\Auth#login
        $admin->loginfailure = 0;
        $admin->logintime = time();
        $admin->loginip = request()->ip();
        $admin->token = Random::uuid();
        $admin->save();
        Session::set("admin", $admin->toArray());
        
        $request = Request::instance();
        Hook::listen("admin_login_after", $request);
    }
}
